/*
 * @Author: wxq 1553421403@qq.com
 * @Date: 2025-01-01 22:32:30
 * @LastEditors: wxq 1553421403@qq.com
 * @LastEditTime: 2025-01-03 09:07:03
 * @FilePath: /smart_gateway/app/app_common.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * 
 */
#include "app_common.h"
#include "stdio.h"
#include "stdlib.h"
#include "sys/time.h"
#include "string.h"
#include "log.h"
long app_common_get_curts_ms()
{
    struct timeval tv;

    // 获取当前时间
    gettimeofday(&tv, NULL);

    // tv.tv_sec:秒 tv.usec:微妙
    return (tv.tv_sec * 1000 + tv.tv_usec / 1000);
}

char *app_common_bytes2hexstr(char *bytes, int len)
{
    char *hexstr = (char *)malloc(len * 2 + 1);
    int i;
    for (i = 0; i < len; i ++)
    {
        sprintf(hexstr + i * 2, "%02X", bytes[i]);
    }
    // hexstr[i] = 0;
    hexstr[len * 2] = 0;

    return hexstr;
}

static char hex2ascii(char hex)
{
    if (hex >= '0' && hex <= '9')
    {
        return hex - '0';
    }
    else if (hex >= 'a' && hex <= 'f')
    {
        return hex - 'a' + 10;
    }
    else if (hex >= 'A' && hex <= 'F')
    {
        return hex - 'A' + 10;
    }
    log_error("hexstr2bytes error %c", hex);
    return -1;
}

int app_common_hexstr2bytes(char *hexstr, char *bytes_buff)
{
    // "61"  高位"6"  低位"1"  -> 6,1   -> 6*16 +1  ->  97 --> 'a'
    for (int i = 0; i < strlen(hexstr); i += 2)
    {
        // 高位
        int high = hex2ascii(hexstr[i]);
        // 低位
        int low = hex2ascii(hexstr[i + 1]);
        // 拼接
        bytes_buff[i / 2] = (high << 4) | low;
    }

    return strlen(hexstr) / 2;
}

void app_common_print_hex(char *hexstr, int len)
{
    for (int i = 0; i < len; i++)
    {
        printf("%02X ", hexstr[i]);
    }
    printf("\n");
}
